<template>
  <!-- 表单上部按钮 -->
  <div class="btn">
    <div class="batch_btn">
      <a-button type="primary" :disabled="!hasSelected" @click="ChangeOperation(40001)"> 批量发布 </a-button>
      <a-button type="primary" :disabled="Deactivate" @click="ChangeOperation(40002)"> 批量停用 </a-button>
    </div>
    <div class="op_btn">
      <a-button type="primary" @click="dowload">码表模板下载</a-button>
      <a-button type="primary">码表导入</a-button>
      <a-button type="primary" @click="addStopwatch(0)">新增码表</a-button>
    </div>
  </div>
  <!-- 表单 -->
  <a-table
    :columns="columns"
    :data-source="table.data"
    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, preserveSelectedRowKeys: true }"
    :row-key="(record:DataItem) => record.stopwatchCode"
    :loading="loading"
    :pagination="pageOptions"
    :locale="{
      cancelSort: '点击取消排序',
      triggerAsc: '点击升序',
      triggerDesc: '点击降序',
    }"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.id === 'title'">
        <span>
          {{ record.title }}
        </span>
      </template>
      <!-- 编号 -->
      <template v-else-if="column.id === 'stopwatchCode'">
        <a-button type="link" style="font-weight: 500; color: #008af7" @click="showModal(record.stopwatchCode, record.stopwatchName, record.stopwatchIllustrate)">{{ record.stopwatchCode }}</a-button>
      </template>
      <!-- 状态 -->
      <template v-else-if="column.id === 'stopwatchStatus'">
        <a-tag :color="record.statusColor">{{ record.stopwatchStatus }}</a-tag>
      </template>
      <!-- 操作 -->
      <template v-else-if="column.id === 'action'">
        <!-- 未发布 -->
        <span v-show="record.stopwatchStatus === '未发布'" class="list_btn">
          <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40001)">
            <template #title>
              <p>是否将码表状态更改为发布</p>
            </template>
            <a-button type="link">发布</a-button>
          </a-popconfirm>
          <a-button type="link" @click="addStopwatch(1, record)">编辑</a-button>
          <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="delStopwatch(record.stopwatchCode)">
            <template #title>
              <p>是否删除码表</p>
            </template>
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </span>
        <!-- 已发布 -->
        <span v-show="record.stopwatchStatus === '已发布'" class="list_btn">
          <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40002)">
            <template #title>
              <p>是否将码表状态更改为停用</p>
            </template>
            <a-button type="link" danger>停用</a-button>
          </a-popconfirm>
        </span>
        <!-- 已停用 -->
        <span v-show="record.stopwatchStatus === '已停用'" class="list_btn">
          <a-popconfirm placement="topRight" ok-text="是" cancel-text="否" @confirm="releaseOrOutage(record, 40001)">
            <template #title>
              <p>是否将码表状态更改为发布</p>
            </template>
            <a-button type="link">发布</a-button>
          </a-popconfirm>
          <a-button type="link" @click="addStopwatch(1, record)">编辑</a-button>
        </span>
      </template>
    </template>
  </a-table>
</template>
<script lang="ts" setup>
  import { DataItem, Key, operationStatus } from '../specification';
  import { changeStopwatchState, deleteStopwatch, downloadStopwatch } from '@/api/test/index';
  import { getListHooks } from '@/hooks/CodeTablesHooks/getstopwatchDataHooks';
  import { getDetailHooks } from '@/hooks/CodeTablesHooks/getStopwatchDetailHooks';

  // 表头
  const columns = [
    {
      title: '码表编号',
      dataIndex: 'stopwatchCode',
      id: 'stopwatchCode',
      width: '10%',
      align: 'center',
    },
    {
      title: '码表名称',
      dataIndex: 'stopwatchName',
      id: 'stopwatchName',
      width: '12%',
      align: 'center',
    },
    {
      title: '码表说明',
      dataIndex: 'stopwatchIllustrate',
      id: 'stopwatchIllustrate',
      width: '30%',
      align: 'center',
    },
    {
      title: '码表状态',
      dataIndex: 'stopwatchStatus',
      id: 'stopwatchStatus',
      width: '10%',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      id: 'updateTime',
      width: '15%',
      align: 'center',
      sorter: {
        compare: (a: any, b: any) => (a.updateTime > b.updateTime ? 1 : -1),
        multiple: 3,
      },
      sortDirections: ['ascend', 'descend'],
    },
    {
      title: '操作',
      id: 'action',
      width: '18%',
      align: 'center',
    },
  ];

  // 第几行是否被选择
  const selectedRowKeys = ref<Key[]>([]);
  // 保存选择后的数据---需要向后端传递的数据
  const selectStopwatch = ref<Object[]>([]);
  // 获取list显示数组
  const { table, loading, getData } = getListHooks();
  // 获取详情
  const { Detail, drawer, dialog, cuStatus, stopwatch } = getDetailHooks();
  // 模板模板下载
  const dowload = async () => {
    const res = await downloadStopwatch();
    //	传入一个二进制流
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    //	获取blob的url地址
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    //	设置文件名， => 在写这个的时候，就是应为没有设置文件名倒是倒是下载下来的是undefiled
    a.download = `码表模板.xlsx`;
    a.href = url;
    a.click();
  };
  // 分页
  const pageOptions = computed(() => {
    return {
      total: table.total,
      current: table.num,
      pageSize: table.size,
      defaultPageSize: 10,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '30'],
      showQuickJumper: true,
      showTotal: () => `共${table.total}条`,
      onChange: (pageNum: number, pageSize: number) => {
        table.num = pageNum;
        table.size = pageSize;
        getData();
      },
    };
  });
  // 点击码表编号出现弹窗
  const showModal = (stopwatchCode: string, stopwatchName: string, stopwatchIllustrate: string) => {
    console.log(`点击率--${stopwatchCode}--${stopwatchCode}`);
    dialog.value = true;
    stopwatch.code = stopwatchCode;
    stopwatch.name = stopwatchName;
    stopwatch.illustrate = stopwatchIllustrate;
    Detail();
  };
  // 按钮是否禁用
  const hasSelected = computed(() => selectedRowKeys.value.length > 0);
  const Deactivate = ref<boolean>(true);
  // 监听被选中的列表状态
  watch(
    () => selectStopwatch.value,
    nv => {
      Deactivate.value = false;
      if (nv.length == 0) {
        Deactivate.value = true;
      } else {
        nv.forEach((item: { [arg: string]: any }) => {
          if (item.stopwatchStatus == '未发布') {
            Deactivate.value = true;
          }
        });
      }

      console.log(' Deactivate.value ' + Deactivate.value);
    },
    { deep: true },
  );
  // 勾选后将勾选数据插入数组
  const onSelectChange = (e: Key[], record: Key[]) => {
    console.log('selectedRowKeys changed: ', e);
    console.log(`${e}-- ${JSON.stringify(record)}`);
    selectedRowKeys.value = e;
    selectStopwatch.value = record;
    console.log(`${JSON.stringify(selectedRowKeys.value)}--${JSON.stringify(selectStopwatch.value)}`);
  };
  //批量按钮操作
  const ChangeOperation = async (e: 40001 | 40002) => {
    loading.value = true;
    const deliverInfo: operationStatus = {
      status: e,
      codeList: selectedRowKeys.value as [string],
    };
    await changeStopwatchState(deliverInfo);
    table.num = 1;
    getData();
    selectedRowKeys.value = [];
    selectStopwatch.value = [];
  };
  // 新增--编辑码表
  const addStopwatch = (perationStatus: number, record?: DataItem) => {
    drawer.value = true;
    cuStatus.value = 0;
    stopwatch.code = '';
    stopwatch.name = '';
    stopwatch.illustrate = '';
    stopwatch.detail = [];
    if (perationStatus == 1 && record != undefined) {
      console.log(`新增--编辑：码表名称：${record.stopwatchName}--码表说明：${record.stopwatchIllustrate}--码表编号：${record.stopwatchCode}`);
      // 编辑
      cuStatus.value = 1;
      stopwatch.code = record.stopwatchCode;
      stopwatch.name = record.stopwatchName;
      stopwatch.illustrate = record.stopwatchIllustrate;
      Detail();
    }
  };
  // 发布、停用按钮
  const releaseOrOutage = async (e: DataItem, status: 40001 | 40002) => {
    const deliverInfo: operationStatus = {
      status: status,
      codeList: [e.stopwatchCode],
    };
    await changeStopwatchState(deliverInfo);
    table.num = 1;
    getData();
  };
  // 删除按钮
  const delStopwatch = async (stopwatchCode: string) => {
    loading.value = true;
    console.log(`删除${stopwatchCode}`);
    await deleteStopwatch(stopwatchCode);
    getData();
  };
</script>

<style lang="less" scoped>
  :deep(.ant-table-thead > tr > th) {
    font-weight: 600;
    background: rgb(238, 238, 238);
  }

  .ant-table-wrapper {
    min-width: 1200px;
    height: 80%;
  }

  .btn {
    display: flex;
    justify-content: space-between;
    margin: 20px 0px;

    .batch_btn {
      display: flex;
      justify-content: space-evenly;
      width: 20%;
    }

    .op_btn {
      display: flex;
      justify-content: space-evenly;
      width: 400px;
    }
  }

  :deep(.ant-table) {
    overflow-y: auto;
    height: calc(100vh - 340px);
    box-shadow: inset 0 -20px 20px -20px #9e9e9e57;

    :deep(.ant-table-row) {
      height: 100px;
    }
  }

  .ant-table-cell {
    .list_btn {
      display: flex;
    }
  }

  .ant-pagination {
    margin-top: 20px;
    margin-left: 35%;
  }
</style>
